package io.geekidea.boot.util.baiwangUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

public class InvoiceOrderNoGenerator {
    private static AtomicInteger sequence = new AtomicInteger(0);
    private static String lastDateStr = "";

    /**
     * 生成开票单号 (格式: yyyyMMddHHmmss + 5位序列号)
     * 每天序列号从1开始重新计数
     *
     * @return 开票单号
     */
    public static String generateOrderNo() {
        LocalDateTime now = LocalDateTime.now();
        String currentDateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        synchronized (InvoiceOrderNoGenerator.class) {
            if (!currentDateStr.equals(lastDateStr)) {
                sequence.set(0);
                lastDateStr = currentDateStr;
            }
            int seq = sequence.incrementAndGet();
            if (seq > 99999) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                return generateOrderNo();
            }
            String timestamp = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String sequenceStr = String.format("%05d", seq);
            return timestamp + sequenceStr;
        }
    }
}